#include <cassert>
#include "VariableNode.h"
#include "..\Expression.h"
#include "..\InternalStruct.h"

using namespace std;

namespace CExpression
{
	void VariableNode::Eval(ExecuteContext &context)
	{
		if(this->currentType==ExecuteRunTimeType::Boolean)
		{
			map<ExpressionString,bool>::iterator iter= context.BoolVariables().find(this->variableName);
			assert(iter!=context.BoolVariables().end());
			context.SetGlobalTempBoolean((*iter).second);
			context.SetTempResultType(ExecuteRunTimeType::Boolean);
		}
		else if(this->currentType==ExecuteRunTimeType::Double)
		{
			map<ExpressionString,double>::iterator iter= context.DoubleVariables().find(this->variableName);
			assert(iter!=context.DoubleVariables().end());
			context.SetGlobalTempNum((*iter).second);
			context.SetTempResultType(ExecuteRunTimeType::Double);
		}
		else
		{
			context.SetError();
			context.SetErrorMsg(TEXT("Variable value must be setted before execute."));
		}
	}

	shared_ptr<Node> VariableNode::Clone(Expression &parent)
	{
		shared_ptr<Node> result;
		std::map< ExpressionString,shared_ptr<VariableNode> >::iterator iter=parent.expData->variableNodes->find(this->variableName);
		if(iter!=parent.expData->variableNodes->end())
		{
			result=iter->second;
		}
		else
		{
			result=shared_ptr<Node>(new VariableNode(this->variableName,this->currentType));
		}
		return result;
	}
}